package com.zorn.core.struts.interceptor;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.zorn.core.provider.ActionSupportProvider;

public class ExceptionInterceptor implements Interceptor {

	private static final long serialVersionUID = 5654492083037954952L;

	@Override
	public void init() {

	}

	@Override
	public void destroy() {

	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		try {
			return invocation.invoke();
		} catch (Exception e) {
			ActionSupportProvider action = (ActionSupportProvider) invocation.getAction();
			HttpServletRequest request = action.getRequest();
			Map<String, Object> ex = new HashMap<String, Object>();

			// Basic info
			ex.put("success", false);
			ex.put("date", new Date());

			// Request info
			ex.put("action", action.getClass().getName());
			ex.put("method", invocation.getProxy().getMethod());
			ex.put("parameters_original", request.getParameterMap());
			ex.put("parameters_parsed", action.getParameterMap());
			ex.put("character_encoding", request.getCharacterEncoding());
			ex.put("locale", request.getLocale());
			ex.put("uri", request.getRequestURI());
			ex.put("url", request.getRequestURL().toString());

			// Exception info
			ex.put("exception", e.getClass().getName());
			ex.put("message", e.getMessage());
			ex.put("stack_trace", e.getStackTrace()[0]);

			action.setJSONObject(ex);

			return ActionSupportProvider.JSON_EXCEPTION;
		}
	}
}
